<template>
    <div class="talk">
        <button @click="getLoveTalk">获取一句土味情话</button>
        <ul v-for="talk in talkStore.talkList" :key="talk.id">
            <li>{{ talk.content }}</li>
        </ul>
    </div>
</template>

<script setup lang="ts" name="LoveTalk">
    import axios from 'axios';
    import { nanoid } from 'nanoid';
    import {useLoveTalkStore} from '../store/loveTalk'

    let talkStore = useLoveTalkStore()

    // $subscribe 当store中数据发生变化时触发
    // 实现网页缓存的效果
    talkStore.$subscribe((mutate, state)=>{
        console.log('talkStore中的数据发生了变化!', mutate, state)
        localStorage.setItem('talkList',JSON.stringify(state.talkList))
    })

    async function getLoveTalk() {
        // 连续解构
        let {data: {content}} = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json")
        let obj = {id:nanoid(), content}
        talkStore.talkList.unshift(obj)
    }


</script>

<style scoped>
.talk {
    background-color: rgb(235, 228, 135);
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
}

button {
    margin: 0 5px;
}
</style>